package com.app.controller;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.common.ReasonForRefundTool;
import com.app.common.Result;
import com.app.model.*;
import com.app.service.*;
import com.app.utils.CheckDeliveryUtil;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.IntegralOrderVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 积分订单
 *
 * @author 16693103420
 * @since 2024-02-01
 */
@Slf4j
@RestController
@RequestMapping("/integralOrder")
public class IntegralOrderController {
    @Autowired
    private IntegralOrderService integralOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AddressService addressService;

    @Autowired
    private BusinessService businessService;


    // 查询列表
    @GetMapping("/getIntegralOrderList")
    public Result getIntegralOrderList(@RequestParam(defaultValue = "0") Integer page,
                                       @RequestParam(defaultValue = "10") Integer limit, String goodsName, Integer status, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用戶不存在");
        }
        Integer userId = userModel.getId();

        IntegralOrderVo IntegralOrderVo = integralOrderService.getUserIntegralOrderList(page, limit, goodsName, status, userId);
        return Result.success(IntegralOrderVo);
    }

    // 查询列表
    @GetMapping("/getAdminIntegralOrderList")
    public Result getAdminIntegralOrderList(@RequestParam(defaultValue = "0") Integer page,
                                            @RequestParam(defaultValue = "10") Integer limit, String goodsName, Integer status, String areaId, String phone) {
        IntegralOrderVo IntegralOrderVo = integralOrderService.getIntegralOrderList(page, limit, goodsName, status, areaId, phone);
        return Result.success(IntegralOrderVo);
    }

    //根据id查询
    @GetMapping("/getIntegralOrderById")
    public Result getIntegralOrderById(Integer id) {
        IntegralOrderModel integralOrder = integralOrderService.getById(id);
        if (integralOrder != null) {
            if (integralOrder.getAddressId() != null) {
                AddressModel addressModel = addressService.getById(integralOrder.getAddressId());
                integralOrder.setAddressModel(addressModel);
            }
            if (integralOrder.getMessage() != null) {
                Object parse = JSON.parse(integralOrder.getMessage());
                integralOrder.setDeliveryVo(parse);
            }
            integralOrder.setMessage(null);
            if (integralOrder.getBusinessId() != null) {
                BusinessModel businessModel = this.businessService.getById(integralOrder.getBusinessId());
                if (businessModel != null) {
                    integralOrder.setBusinessAddress(businessModel.getAddress());
                    integralOrder.setBusinessName(businessModel.getBusinessName());
                }

            }
        }
        return Result.success(integralOrder);
    }

    //新增和修改
    @PostMapping("/addAndUpdateIntegralOrder")
    public Result addAndUpdateIntegralOrder(@RequestBody IntegralOrderModel integralOrderModel) {
        if (integralOrderModel.getId() != null && integralOrderModel.getId() > 0) {
            integralOrderModel.setUpdateTime(CommonHelp.getNowTimestamp());
            integralOrderService.updateById(integralOrderModel);
            return Result.success("修改成功");
        } else {
            integralOrderModel.setOrderSn(IdUtil.fastSimpleUUID());
            integralOrderModel.setCreateTime(CommonHelp.getNowTimestamp());
            integralOrderService.save(integralOrderModel);
            return Result.success("添加成功");
        }
    }

    //根据id删除
    @GetMapping("/delIntegralOrder")
    public Result delIntegralOrder(Integer id) {
        integralOrderService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 获取类别列表
     *
     * @return {@link Result}
     */
    @GetMapping("/getCategoryList")
    public Result getCategoryList() {
        QueryWrapper<CategoryModel> categoryModelQueryWrapper = new QueryWrapper<>();
        categoryModelQueryWrapper.eq("pid", 56);
        List<CategoryModel> modelList = categoryService.list(categoryModelQueryWrapper);
        return Result.success(modelList);
    }

    /**
     * 确认收货
     *
     * @param orderSn 订购sn
     * @return {@link Result}
     */
    @GetMapping("/confirmReceipt")
    public Result confirmReceipt(String orderSn) {
        if (integralOrderService.confirmReceipt(orderSn)) {
            return Result.success("收货成功");
        } else {
            return Result.error(201, "订单不存在");
        }
    }

    //获取快递信息
    @GetMapping("/getMessage")
    public Result getMessage() {
//        String delivery = CheckDeliveryUtil.getCheckDelivery("SF1164071485431", "SFEXPRESS");
//
//        return Result.success(delivery);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<IntegralOrderModel> integralOrderModelQueryWrapper = new QueryWrapper<>();
            integralOrderModelQueryWrapper.eq("status", 2);
            List<IntegralOrderModel> orderModelList = integralOrderService.list(integralOrderModelQueryWrapper);
            for (IntegralOrderModel integralOrderModel : orderModelList) {
                if (integralOrderModel.getStatus() == 2) {
                    if (integralOrderModel.getExpressCompany() != null && integralOrderModel.getTrackingNumber() != null) {
                        CategoryModel categoryModel = categoryService.getById(integralOrderModel.getExpressCompany());
                        if (categoryModel != null) {
                            if ("顺丰".equals(categoryModel.getName()) || "丰网速运".equals(categoryModel.getName())) {
                                AddressModel addressModel = addressService.getById(integralOrderModel.getAddressId());
                                if (addressModel != null) {
                                    String delivery = CheckDeliveryUtil.getCheckDelivery(integralOrderModel.getTrackingNumber() + ":" + addressModel.getPhone().substring(addressModel.getPhone().length() - 4), categoryModel.getReferred());
                                    JSONObject jsonObject = JSON.parseObject(delivery);
                                    if (jsonObject.containsKey("deliverystatus")) {
                                        if (jsonObject.get("deliverystatus").equals(3)) {
                                            if (jsonObject.containsKey("updateTime")) {
                                                Date date1 = sdf.parse(jsonObject.get("updateTime").toString());
                                                if (isOutTime(date1)) {
                                                    integralOrderModel.setStatus(3);
                                                }
                                            }
                                        }
                                    }
                                    integralOrderModel.setMessage(delivery);
                                    integralOrderService.updateById(integralOrderModel);
                                }
                            } else {
                                String delivery = CheckDeliveryUtil.getCheckDelivery(integralOrderModel.getTrackingNumber(), categoryModel.getReferred());
                                JSONObject jsonObject = JSON.parseObject(delivery);
                                if (jsonObject.containsKey("deliverystatus")) {
                                    if (jsonObject.get("deliverystatus").equals(3)) {
                                        if (jsonObject.containsKey("updateTime")) {
                                            Date date1 = sdf.parse(jsonObject.get("updateTime").toString());
                                            if (isOutTime(date1)) {
                                                integralOrderModel.setStatus(3);
                                            }
                                        }
                                    }
                                }
                                integralOrderModel.setMessage(delivery);
                                integralOrderService.updateById(integralOrderModel);
                            }
                        }
                    }
                }
            }
            return Result.success("成功");
        } catch (Exception e) {
            log.error("定时任务出错", e);
            return Result.success(e);
        }
    }

    public static boolean isOutTime(Date data) throws Exception {
        //24小时
        long house = 60 * 60 * 24;
        //系统当前时间,
        long currentTime = System.currentTimeMillis() / 1000;
        //业务时间
        long endTime = data.getTime() / 1000;
        if ((endTime + house) < currentTime) {
            log.info("超过了24小时");
            return true;
        } else {
            log.info("没有超过");
            return false;
        }
    }

    /**
     * 小程序退款
     *
     * @param orderSn 订购sn
     * @return {@link Result}
     */
    @GetMapping("/refund")
    public Result refund(String orderSn, Integer type) {
        return integralOrderService.refund(orderSn, type);
    }


    /**
     * 取消线下积分商品订单
     *
     * @param orderSn 订购sn
     * @return {@link Result}
     */
    @GetMapping("/cancelOrderOfflineIntegralGoods")
    @Transactional(rollbackFor = Exception.class)
    public synchronized Result cancelOrderOfflineIntegralGoods(String orderSn) {
        return integralOrderService.cancelOrderOfflineIntegralGoods(orderSn);
    }





    @GetMapping("/refundReview")
    @Transactional(rollbackFor = Exception.class)
    public Result refundReview(String orderSn, Integer status, String refundRemarks) {
        if (integralOrderService.refundReview(orderSn, status, refundRemarks)) {
            return Result.success("取消成功");
        } else {
            return Result.error(201, "订单不存在");
        }
    }

    @GetMapping("/requireReason")
    public Result requireReason() {
        ReasonForRefundTool reasonForRefundTool = new ReasonForRefundTool();
        return Result.success(reasonForRefundTool);
    }


    //线下核销商品订单
    @PostMapping("/writeOffIntegralOrder")
    public Result writeOffIntegralOrder(@RequestBody IntegralOrderModel integralOrderModel, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel userModel = userService.getUserByOpenid(openId);
        if (userModel == null) {
            return Result.error(405, "用戶不存在");
        }
        return integralOrderService.writeOffIntegralOrder(integralOrderModel, userModel);
    }
}

